<template>
  <current>
    <div class="common-container">
      <head-title is-detail title="访视" :link-path="linkPath" />
      <div class="content-wrap">
        <div class="content">
          <div v-loading="state.subLoading" class="content-left ym-box">
            <div v-if="state.subjectDetail">
              <div class="info-item base-info">
                <base-info :info="state.subjectDetail" />
              </div>
              <div class="add-wrap">
                <el-button type="primary" @click="addVisit">
                  添加新访视
                  <el-icon class="el-icon--right">
                    <Plus />
                  </el-icon>
                </el-button>
              </div>
              <div class="visit-list-wrap">
                <el-row v-if="state.visitList.length > 0" class="visit-list">
                  <el-col
                    v-for="item in state.visitList"
                    :key="item.vid"
                    class="visit-item"
                    :class="{ 'is-active': state.currentVisit.vid === item.vid }"
                  >
                    <visit-item
                      :info="item"
                      :status-data="state.statusObj"
                      @click="clickVisit(item)"
                    />
                  </el-col>
                </el-row>
                <div v-else style="height: 200px">
                  <empty-block />
                </div>
              </div>
            </div>
            <empty-block v-else />
          </div>
          <detail
            v-if="state.visitList.length > 0"
            ref="detailRef"
            v-loading="state.visitDetailLoading"
            class="content-right ym-box"
            :detail="state.detail"
            :dom-ref="['#detail', '#time', '#viewer', '#issue', '#assess']"
            :show-close="false"
            @search="getSingleVisitDetail(state.currentVisit.vid)"
          >
            <template #operator>
              <el-button
                type="primary"
                size="small"
                :disabled="state.currentVisit.status >= STATUS_MAP.taskWait"
                @click="edit"
                >编辑</el-button
              >
              <el-button
                v-if="state.currentVisit.status < STATUS_MAP.taskWait"
                type="primary"
                size="small"
                @click="addViewer"
                >上传影像</el-button
              >
              <el-button v-if="!submitDisabled" type="primary" size="small" @click="submit"
                >提交评估</el-button
              >
              <el-button
                v-if="state.currentVisit.status === STATUS_MAP.qcIssue"
                type="primary"
                size="small"
                >提交复审</el-button
              >
              <el-button
                type="primary"
                size="small"
                @click="handleOpenViewer(state.currentVisit.vid)"
                >查看影像</el-button
              >
              <el-button
                type="primary"
                size="small"
                @click="getSingleVisitDetail(state.currentVisit.vid)"
                >刷新</el-button
              >
            </template>
          </detail>
          <div v-else style="flex: 1">
            <div style="height: 100%">
              <empty-block />
            </div>
          </div>
        </div>
      </div>
    </div>
    <add-dialog
      v-model:visible="state.dialogVisible"
      :sub-id="subId"
      :is-add="state.isAdd"
      :detail="state.visitForm"
      :centre="state.subjectDetail?.centre"
      @search="handleAddSuccess"
    />
    <add-viewer-dialog
      v-model:visible="state.viewerDialogVisible"
      :project-id="pid"
      :centre-id="state.subjectDetail?.centreId"
      :visit-id="state.currentVisit.vid"
      @search="getSingleVisitDetail(state.currentVisit.vid)"
    />
  </current>
</template>

<script lang="ts" setup>
import { computed, nextTick, reactive, ref, watch } from 'vue'
// import QueryApi from '@/api/query'
import { useRoute } from 'vue-router'

import { ElMessage } from 'element-plus'

import BaseInfo from '../components/BaseInfo.vue'
import Detail from '@/components/CommonDetail/index.vue'
import EmptyBlock from '@/components/EmptyBlock/index.vue'
import HeadTitle from '@/components/HeaderTitle/index.vue'
import Current from '../../current/index.vue'
import AddDialog from './addDialog.vue'
import AddViewerDialog from './addViewerDialog.vue'
import VisitItem from './visitCard.vue'

// import { getVisitList, getVisitDicom, submitVisit, updateVisitRemark } from '@/api/visit'
import { getStatus } from '@/api/help'
import EdcApi from '@/api/project/edc'
import SubjectApi from '@/api/project/subject'
import VisitApi from '@/api/project/visit'

import { openViewer } from '@/utils/common/openViewer'

import { DCM_MODULE_FLAG_MAP, PAGE_FLAG, STATUS_MAP } from '@/configs/codeMaps'
import IBaseObj from '#/index'

const route = useRoute()
const { pid, pname, subId }: IBaseObj = route.query

const linkPath = `/project/subject?pid=${pid}&pname=${pname}`

const state: IBaseObj = reactive({
  subjectDetail: null,
  subLoading: false,
  subjectList: [],
  visitList: [],
  visitLoading: false,
  visitDetailLoading: false,
  currentVisit: {
    vid: '',
  },
  dicomList: [],
  dialogVisible: false,
  isAdd: true,
  viewerDialogVisible: false,
  dicomLoading: false,
  statusObj: [],
  visitForm: {},
  detail: null,
})

const submitDisabled = computed(() => {
  // 102200 待提交状态
  return state.dicomList?.length === 0 || state.currentVisit.status !== STATUS_MAP.submitWait
})

watch(
  () => state.currentVisit.vid,
  (val) => {
    if (val) {
      getSingleVisitDetail(val)
      // state.dicomList = []
      // getVisitDicomData(val)
    } else {
      // state.dicomList = []
    }
  }
)

const addVisit = () => {
  state.dialogVisible = true
}
// 添加修改访视成功
const handleAddSuccess = () => {
  if (state.isAdd) {
    getSubjectDetail()
    searchVisit()
  } else {
    getVisitDetail(subId, false)
  }
}

// 编辑访视
const edit = () => {
  state.visitForm = { ...state.currentVisit }
  state.dialogVisible = true
  state.isAdd = false
}

// 提交
const submit = async () => {
  // const ret = await submitVisit(state.currentVisit.vid)
  // if (ret.data) {
  //   ElMessage({ message: '提交成功！', type: 'success' })
  //   getVisitDetail(subId, false)
  // }
}

// 查看影像
const handleOpenViewer = (vid: string) => {
  openViewer({
    moduleFlags: DCM_MODULE_FLAG_MAP.chakan,
    vid,
  })
}

const addViewer = () => {
  state.viewerDialogVisible = true
}

const formatStatus = (status: number) => {
  const item: any = state.statusObj.find((v: any) => status <= v.statusEnd && status >= v.status)
  if (item) {
    return item
  }
  return null
}

/**
 * init 是否需要重新设置选中
 */
const getVisitDetail = async (subId: string, init = true) => {
  state.visitLoading = true
  try {
    const ret = await VisitApi.getVisitInfoList(subId)
    state.visitList = ret || []
    state.visitList.forEach((v: any) => {
      // v.statusObj = formatStatus(v.status)

      v.statusObj = { color: 'gray', value: '待处理' }
    })

    if (state.visitList.length > 0 && init) {
      state.currentVisit = state.visitList[0]
    } else {
      if (state.currentVisit.vid) {
        state.currentVisit = state.visitList.find((v: any) => v.vid === state.currentVisit.vid)
      }
    }
  } finally {
    state.visitLoading = false
  }
}

const searchVisit = () => {
  getVisitDetail(subId)
}

// 获取status
const getStatusData = async () => {
  // const ret = await getStatus(PAGE_FLAG.visit)
  // state.statusObj = ret || []
}

// 获取受试者详情
const getSubjectDetail = async () => {
  if (subId) {
    state.subLoading = true
    try {
      const ret = await SubjectApi.getSubjectById(subId)
      state.subjectDetail = ret || null
      getVisitDetail(subId)
    } finally {
      state.subLoading = false
    }
  }
}

const detailRef = ref()

const clickVisit = (val: IBaseObj) => {
  const lastSub = state.currentVisit
  if (lastSub.vid === val.vid) {
    return
  }
  state.currentVisit = val
}

const getSingleVisitDetail = (vid: string) => {
  state.visitDetailLoading = true

  Promise.all([VisitApi.getVisitInfo(vid), EdcApi.getDicom(vid)])
    .then((result) => {
      state.visitDetailLoading = false
      const dicomList = result[1] || []
      // const issueList = result[1].data || []
      state.detail = {
        ...state.currentVisit,
        dicom: null,
        issue: null,
      }
      if (dicomList.length > 0) {
        state.detail.dicom = dicomList[0]
      }
      // if (issueList.length > 0) {
      //   state.detail.issue = issueList
      // }
      nextTick(() => {
        detailRef.value.getDomTop()
      })
    })
    .catch(() => {
      state.visitDetailLoading = false
    })

  // Promise.all([getVisitDicom(vid), QueryApi.getQueryList(vid)]).then(result => {
  //   state.visitDetailLoading = false
  //   const dicomList = result[0].data || []
  //   const issueList = result[1].data || []
  //   state.detail = {
  //     ...state.currentVisit,
  //     dicom: null,
  //     issue: null
  //   }
  //   if (dicomList.length > 0) {
  //     state.detail.dicom = dicomList[0]
  //   }
  //   if (issueList.length > 0) {
  //     state.detail.issue = issueList
  //   }
  //   nextTick(() => {
  //     detailRef.value.getDomTop()
  //   })
  // }).catch(() => {
  //   state.visitDetailLoading = false
  // })
}

// const getVisitDicomData = async (vid: string) => {
//   state.dicomLoading = true
//   try {
//     const ret = await getVisitDicom(vid)
//     state.dicomList = ret.data
//   } finally {
//     state.dicomLoading = false
//   }
// }

/* remark start */
const remarkState = reactive({
  remark: '',
  visible: false,
})

const addRemark = () => {
  remarkState.visible = true
  remarkState.remark = state.currentVisit.remark
}

const cancelRemark = () => {
  remarkState.visible = false
  remarkState.remark = ''
}

const submitRemark = async () => {
  // const ret = await updateVisitRemark({
  //   remark: remarkState.remark,
  //   vid: state.currentVisit.vid * 1,
  // })
  // if (ret) {
  //   state.currentVisit.remark = remarkState.remark
  //   remarkState.visible = false
  // }
}
/* remark end */

const init = () => {
  getSubjectDetail()
  getStatusData()
}
init()
</script>

<style lang="scss" scoped>
.btn-wrap {
  margin: 10px 0;
}

.search-wrap {
  display: flex;
  justify-content: space-between;
  text-align: right;
}

.content {
  display: flex;
  padding-top: 10px;

  & > div {
    height: calc(100vh - 80px);
    overflow: auto;
    @include scroll-bar;
  }

  &-left {
    display: flex;
    flex-direction: column;
    // justify-content: center;
    align-items: center;
    width: 340px;
    // width: 25%;
    // min-width: 340px;
    padding: 20px 0;
    // padding: 20px 15px;
    // padding: 20px 15px;
    // margin-right: 15px;
    border-right: 1px solid var(--table-border);
    border-radius: 6px 0 0 6px;

    .base-info {
      margin: 0 auto;

      .info-wrap {
        background: transparent;
      }

      :deep(.progress-wrap) {
        .el-progress {
          &-bar {
            &__outer {
              background: var(--el-border-color-lighter);
            }
          }
        }
      }
    }

    .info-item {
      display: flex;
      width: 300px;
      height: 200px;
      flex-direction: column;
      justify-content: center;

      & + .info-item {
        margin-top: 10px;
      }
    }

    .add-wrap {
      width: 100%;
      padding: 10px;
      margin: 10px 0;
      text-align: center;
      border-top: 1px solid var(--table-border);
      border-bottom: 1px solid var(--table-border);

      .el-button {
        // display: flex;
        // align-items: center;

        .el-icon {
          vertical-align: -0.15em;
        }
      }
    }

    .visit {
      &-list {
        justify-content: center;

        .visit__box {
          width: 300px;
        }
      }
    }
  }

  &-right {
    flex: 1;
    // padding: 20px 15px;
    padding: 10px;
    border-radius: 0 6px 6px 0;
  }
}

.visit {
  &-list {
    flex-wrap: wrap;
  }

  &-item {
    flex-basis: auto;
    margin-bottom: 10px;
  }
}

.visit-info-box {
  height: 100%;
  .visit {
    &-title {
      padding-left: 4px;
      font-size: 22px;
      font-weight: 600;
      line-height: 40px;
      color: #f9b034;

      &-wrap {
        display: flex;
        height: 40px;
        align-items: center;
        justify-content: space-between;
        // justify-content: flex-end;
      }
    }

    &-info {
      display: flex;
    }
  }

  .icon {
    position: absolute;
    top: 6px;
    right: 6px;
  }

  .check {
    &-list {
      flex: 1;
    }
  }

  .other {
    &-info {
      width: 20%;
      min-width: 200px;
      margin-left: 10px;
    }

    &-item {
      display: flex;
      align-items: center;
      justify-content: space-between;
      // height: 80px;
      padding: 15px 20px;
      margin-bottom: 10px;
      background: var(--background-color-1);
      border-radius: 6px;

      &__title {
        margin-bottom: 15px;
        line-height: 24px;
      }

      &__time {
        font-size: 16px;
        color: var(--color-2);
      }
    }
  }

  .remark-item {
    flex-direction: column;
    align-items: flex-start;

    .remark-content {
      word-break: break-all;
    }

    .other-item__title {
      display: flex;
      width: 100%;
      margin-bottom: 15px;
      align-items: center;
      justify-content: space-between;

      .el-icon {
        font-size: 16px;
        cursor: pointer;
      }
    }

    .remark-btn {
      margin-top: 5px;
      text-align: right;
    }
  }
}

.add-dicom-card {
  display: flex;
  padding: 20px 0;
  margin-bottom: 10px;
  font-size: 18px;
  cursor: pointer;
  background: var(--background-color-1);
  border-radius: 6px;
  justify-content: center;
  align-items: center;

  .el-icon {
    margin-right: 5px;
    font-size: 18px;
  }
}
</style>
